<?php

namespace app\api\controller;

use app\api\model\ProductStock;
use think\Collection;
use think\Db;
use think\facade\Request;
use app\api\model\Product;

class CommodityStock extends Common
{
    protected const TTL = 30;

    public function index(Request $request, \app\api\model\Commodity $commodity)
    {
        $data = array_filter($request::param());
        $where = [];
        if (isset($data['name'])) {
            $where[] = ['name|item|goods_code', 'LIKE', '%' . $data['name'] . '%'];
        }
        if (!empty($data['brand'])) {
            $where[] = ['brand', '=', $data['brand']];
        }
        if (!empty($data['category'])) {
            $where[] = ['category', '=', $data['category']];
        }
        if (!empty($data['style'])) {
            $where[] = ['style', '=', $data['style']];
        }
        if (!empty($data['material'])) {
            $where[] = ['material', '=', $data['material']];
        }
        if (!empty($data['unit'])) {
            $where[] = ['unit', '=', $data['unit']];
        }
        if (!empty($data['year'])) {
            $where[] = ['year', '=', $data['year']];
        }
        if (!empty($data['season'])) {
            $where[] = ['season', '=', $data['season']];
        }
        $arr = [];
        if (!empty($data['color'])) {
            //$where[] = ['color', '=', $data['color']];
            $arr[] = Product::where('color', $data['color'])->fetchCollection()->select()->column('commodity_id');
        }
        if (!empty($data['sizes'])) {
            //$where[] = ['size', '=', $data['sizes']];
            $arr[] = Product::where('size', $data['sizes'])->fetchCollection()->select()->column('commodity_id');
        }
        if (!empty($data['warehouse'])) {
//            $where[] = ['warehouse', '=', $data['warehouse']];
            $arr[] = ProductStock::where('warehouse', $data['warehouse'])
                ->fetchCollection()->select()->column('commodity_id');
        }
        if (isset($data['max']) && isset($data['min'])) {
            //$where[] = ['stock', 'between', [$data['min'],$data['max']]];
            $arr[] = ProductStock::where('stock', 'between', [$data['min'], $data['max']])
                ->fetchCollection()->select()->column('commodity_id');
        }
        if (!empty($arr)) {
            $arr1 = [];
            foreach ($arr as $v) {
                foreach ($v as $v1) {
                    $arr1[] = $v1;
                }
            }
            $arr1 = array_unique($arr1);
            $where[] = ['id', 'in', $arr1];
            if (isset($data['max']) && isset($data['min'])) {
                $where[] = ['stock', 'between', [$data['min'], $data['max']]];
            }
        }
        $res = $commodity->index(
            $where,
            $request::param('page'),
            $request::param('size'),
            ['products' => ['stock']]
        );
        $put_num = [];
        $warning = [];
        $cost = [];
        $res = $res->each(function ($comm) {
            // 库存
            if (!empty(array_filter($comm->products->column('stock')))) {
                $info['put_in'] = array_sum(array_map(function ($stock) {
                    return $stock['put_in'];
                }, $comm->products->column('stock')));
                $info['stock'] = array_sum(array_map(function ($stock) {
                    return $stock['stock'];
                }, $comm->products->column('stock')));
                $info['put_out'] = array_sum(array_map(function ($stock) {
                    return $stock['put_out'];
                }, $comm->products->column('stock')));
                $info['stock_num'] = $info['stock'] + $info['put_out'];
                $info['ava_stock'] = $info['stock'] + $info['put_in'] - $info['put_out'];
                $put_num[] = $info['stock'];
                array_map(function ($product) {
                    if ($product['stock_warning'] == 0) {
                        $a = $product['stock']['stock'];
                        if ($a >= $product['stock_upper'] || $a <= $product['stock_lower']) {
                            $warning[] = true;
                        }
                    }
                }, $comm->products->toArray());
                //print_r($comm->purchase_price);die;
                array_map(function ($stock) use ($comm) {
                    $cost[] = $stock['stock']['stock'] * $comm->purchase_price;
                }, $comm->products->toArray());
            } else {
                $info['stock'] = 0;
                $info['put_in'] = 0;
                $info['put_out'] = 0;
                $info['stock_num'] = 0;
                $info['ava_stock'] = 0;
            }
            $comm['info'] = $info;
            return $comm;
        });
        $res = $res->toArray();
        $res['product_total'] = count($res);
        $res['stock'] = array_sum($put_num);
        $res['warning'] = count($warning);
        $res['cost'] = array_sum($cost);
        return $this->returnJson(200, 'success', $res);
    }

    public function show($id, \app\api\model\ProductStock $productStock)
    {
        $res = \app\api\model\Commodity::with(['products' => ['stock']])->find($id);
        $stockType = Request::param('type', 0);
        $data = $res->products->column('stock');
        $products = $res->products->column('id');
        $color = $res->products->map(function ($v) {
            return $v->getData('color');
        });
        $size = $res->products->map(function ($v) {
            return $v->getData('size');
        });
        $warehouse = array_unique($res->products()->stock()
            ->whereIn('product_id', $products)->fetchCollection()->column('warehouse'));
        $warehouse = array_map(function ($v) use ($data, $products, $color, $size, $stockType, $res) {
            $w['warehouse_name'] = \app\api\model\Warehouse::cache(self::TTL)->find($v)['name'];
            $w['warehouse'] = $v;
            foreach ($data as $ket => $item) {
                if ($item['warehouse'] == $v) {
                    $w['stock'][] = self::getStock($item, $stockType);
                    $w['product'][] = $item['product_id'];
                    foreach ($color as $c) {
                        $dd =  $res->products()->stock()->where('warehouse', $v)->whereIn(
                            'product_id',
                            Product::where('color', $c)->whereIn('id', $products)
                                ->fetchCollection()->column('id')
                        )->find();
                        $DDDD = [
                            'color_name' => \app\api\model\Goods\Speci\Color::cache(self::TTL)->find($c)->name,
                            'color' => intval($c),
                            'stock' => self::getStock($dd, $stockType),
                            'product' => $item['product_id']
                        ];
                        foreach ($size as $s) {
                            $ss = ProductStock::where('warehouse', $v)->whereIn(
                                'product_id',
                                Product::where('size', $s)->where('color', $c)
                                    ->whereIn('id', $products)
                                    ->fetchCollection()->column('id')
                            )->find();
                            $DDDD['size'][] =  [
                                'size_name' => \app\api\model\Goods\Speci\Size::cache(self::TTL)->find($s)->name,
                                'size' => intval($s),
                                'stock' => self::getStock($ss, $stockType),
                                'product' => $item['product_id']
                            ];
                        }
                        $DDDD['size'] = array_unique($DDDD['size'], SORT_REGULAR);
                        $w['color'][] = $DDDD;
                    };
                } else {
                    $w['stock'][] = 0;
                    $w['color'] = [];
                    $w['size'] = [];
                }
            }
            $w['stock'] = array_sum($w['stock']);
            $w['color'] = array_unique($w['color'], SORT_REGULAR);
            return $w;
        }, $warehouse);
        return $this->returnJson(200, 'success', array_merge(['info' => $warehouse], $res->toArray()));
    }

    /**
     * @param $data
     * @param $type
     * @return int
     */
    private static function getStock($data, $type)
    {
        switch ($type) {
            // 当前
            case 0:
                return $data['stock'];
                break;
                // 可用
            case 1:
                return $data['stock'] + $data['put_in'];
                break;
                // 待入库
            case 2:
                return $data['put_in'];
                break;
                //  待出库
            case 3:
                return $data['put_out'];
                break;
            default:
                return 0;
                break;
        }
    }
}
